<template>
  <div>
    <!--引用表格-->
   <BasicTable @register="registerTable">
     <!--插槽:table标题-->
      <template #tableTitle>
          <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
      </template>
       <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--字段回显插槽-->
      <template #htmlSlot="{text}">
         <div v-html="text"></div>
      </template>
      <!--省市区字段回显插槽-->
      <template #pcaSlot="{text}">
         {{ getAreaTextByCode(text) }}
      </template>
      <template #fileSlot="{text}">
         <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
         <a-button v-else :ghost="true" type="primary" preIcon="ant-design:download-outlined" size="small" @click="downloadFile(text)">下载</a-button>
      </template>
     <template #img="{ text }">
       <TableImg :size="60" :simpleShow="true" :imgList="text" />
     </template>
     <template #logo="{ text }">
       <TableImg :size="60" :imgList="text" />
     </template>
    </BasicTable>
    <!-- 表单区域 -->
    <TProductModal @register="registerModal" @success="handleSuccess"></TProductModal>
    <ProductGrowthcycleTable @register="productGrowthcycleDrawer"> </ProductGrowthcycleTable>
    <ProductOperationTable @register="productOperationDrawer"> </ProductOperationTable>
  </div>
</template>

<script lang="ts" name="TProduct-tProduct" setup>
  import {ref, computed, unref} from 'vue';
  import {BasicTable, useTable, TableAction,TableImg} from '/@/components/Table';
  import {useModal} from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import TProductModal from './components/TProductModal.vue'
  import {columns, searchFormSchema} from './TProduct.data';
  import {list, deleteOne, batchDelete, getImportUrl,getExportUrl} from './TProduct.api';
  import { downloadFile } from '/@/utils/common/renderUtils';
  import ProductGrowthcycleTable  from "./components/ProductGrowthcycleTable.vue";
  import {useDrawer} from "/@/components/Drawer";
  import ProductOperationTable from "./components/ProductOperationTable.vue";
  import { defHttp } from '/@/utils/http/axios';
  import {Modal,InputNumber } from "ant-design-vue";
  const checkedKeys = ref<Array<string | number>>([]);
  // 注册抽屉
  const [productGrowthcycleDrawer, { openDrawer: openProductGrowthcycleDrawer }] = useDrawer();
  const [productOperationDrawer, { openDrawer: openProductOperationDrawer }] = useDrawer();
  //注册model
  const [registerModal, {openModal}] = useModal();
  //注册table数据
  const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '农产品信息',
           api: list,
        rowKey: 'no',
        beforeFetch:(params)=>{
           params.column = 'no';
           params.order = 'asc'
          return params;
        },
        afterFetch: async (data) => {
          if (data) {
            let ids = data.map(item => item.no).join(",");

            const res = await defHttp.get({
              url: "/deployContract/listByProductIds",
              params: { productIds: ids, isMap: true }
            }, { joinParamsToUrl: true, isTransformResponse: false });

            if (res.success) {
              // 赋值区块链账号
              data.forEach(item => {
                let cng = res.result.filter(val => val.productName == item.no)
                if (cng.length) {
                  item.contractAddress = cng[0].contractAddress;
                  item.balance = cng[0].balance;
                }
              });
            }

            console.log("加载完成");
            return data;
          }
        },
           columns,
           canResize:false,
           formConfig: {
              //labelWidth: 120,
              schemas: searchFormSchema,
              autoSubmitOnEnter:true,
              showAdvancedButton:true,
              fieldMapToNumber: [
              ],
              fieldMapToTime: [
              ],
            },
           actionColumn: {
               width: 260 ,
               fixed:'right'
            },
      },
       exportConfig: {
            name:"农产品信息",
            url: getExportUrl,
          },
          importConfig: {
            url: getImportUrl,
            success: handleSuccess
          },
  })

  const [registerTable, {reload},{ rowSelection, selectedRowKeys }] = tableContext

   /**
    * 新增事件
    */
  function handleAdd() {
     openModal(true, {
       isUpdate: false,
       showFooter: true,
     });
  }
   /**
    * 编辑事件
    */
  function handleEdit(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: true,
     });
   }
   /**
    * 详情
   */
  function handleDetail(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 删除事件
    */
  async function handleDelete(record) {
     await deleteOne({no: record.no}, handleSuccess);
   }
   /**
    * 批量删除事件
    */
  async function batchHandleDelete() {
     await batchDelete({ids: selectedRowKeys.value}, handleSuccess);
   }
   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }
  /**
   * 生长周期选择
   */
  function handleGrowthcycle(record: Recordable) {
    openProductGrowthcycleDrawer(true, record);
  }

  /**
   * 农事操作
   */
  function handleOperation(record: Recordable) {
    openProductOperationDrawer(true, record);
  }

  /**
   * 创建区块链合约
   */
  function createCngContact(record){
    Modal.confirm({
      title: '确认创建CNG合约',
      content: '是否创建CNG合约',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return defHttp.post({ timeout:60*1000,url:"/deployContract/addByPorduct", data: {productNo:record.no} }, { joinParamsToUrl: true }).then(() => {
          handleSuccess();
        });
      },
    });
  }


  /**
      * 操作栏
      */
  function getTableAction(record){
       return [
         {
           label: '编辑',
           onClick: handleEdit.bind(null, record),
         },
         {
           label: '生长周期',
           onClick: handleGrowthcycle.bind(null, record),
         },
         // {
         //   label: '农事操作',
         //   onClick: handleOperation.bind(null, record),
         // },
       ]
   }
     /**
        * 下拉操作栏
        */
  function getDropDownAction(record){
       return [
         {
           label: '详情',
           onClick: handleDetail.bind(null, record),
         },
         {
           label: '创建CNG链合约',
           onClick: createCngContact.bind(null, record),
           ifShow: () => {
             return !record.contractAddress;
           },
         },
         {
           label: '删除',
           popConfirm: {
             title: '是否确认删除',
             confirm: handleDelete.bind(null, record),
           }
         }
       ]
   }


</script>

<style scoped>

</style>
